package com.example.teamwork1.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Component
@Data
public class EmailUtil {
    private static String from;
    private static String pwd;
    private static String host;
//    private static String port;

    private static JavaMailSenderImpl mailSender;

    @Autowired(required = false)
    public void setMailSender(JavaMailSenderImpl mailSender){
        EmailUtil.mailSender = mailSender;
    }

    @Value("${spring.mail.username}")
    public void setFrom(String from){
        EmailUtil.from = from;
    }
    @Value("${spring.mail.password}")
    public void setPwd(String pwd){
        EmailUtil.pwd = pwd;
    }
    @Value("${spring.mail.host}")
    public void setHost(String host){
        EmailUtil.host = host;
    }
//    @Value("${spring.mail.port}")
//    public void setPort(String port){
//        EmailUtil.port = port;
//    }

    /**
     * @Title: sendEmail
     * @Description: TODO(发送邮件)
     * @param @param subject  要发送标题
     * @param @param emailTo  要发送的邮箱
     * @param @param text 发送的内容
     * @return boolean 返回类型 true：成功,false:失败
     */
    public static boolean sendEmail(String emailTo , String subject, String text){
        boolean flg = false;

        if(StringUtils.isEmpty(subject) || StringUtils.isEmpty(emailTo) || StringUtils.isEmpty(text)){
            log.error("=======数据不全，发送失败");
            return flg;
        }

        try {
            flg = sendEmailCommon(emailTo, subject, text);
        }catch (Exception e){
            log.error("=======发邮件异常：目标邮箱："+emailTo+","+e.getMessage());
            e.printStackTrace();
            flg = false;
        }

        return flg;
    }

    public static boolean sendEmailCommon(String emailTo, String title,String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(emailTo);
            message.setSubject(title);
            message.setText(content);
            message.setSentDate(new Date());
            message.setCc(from);	// 设置抄送，出现过发不出去，设置后就可以了
            mailSender.send(message);
            log.info("=======发邮件成功：目标邮箱："+emailTo+"，标题："+title);
            return true;
        }catch (Exception e){
            log.error("=======发邮件异常：目标邮箱："+emailTo+","+e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
